package cn.wuweixiang.es.service.impl;

import cn.wuweixiang.es.constant.ModelConstant;
import cn.wuweixiang.es.model.Model;
import cn.wuweixiang.es.service.ModelService;
import io.searchbox.client.JestClient;
import io.searchbox.client.JestResult;
import io.searchbox.core.Bulk;
import io.searchbox.core.Index;
import io.searchbox.core.Search;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

/**
 * The type Model service.
 *
 * @author weixiang.wu
 */
@Service
public class ModelServiceImpl implements ModelService {
	
	private static final Logger logger = LoggerFactory.getLogger(ModelServiceImpl.class);
	
	@Resource
	private JestClient jestClient;
	
	@Override
	public void saveModel(Model model) {
		Index index = new Index.Builder(model).index(ModelConstant.INDEX_NAME).type(ModelConstant.TYPE).build();
		try {
			jestClient.execute(index);
			logger.info("ElasticSearch插入完成");
		} catch (IOException e) {
			logger.error(e.getMessage());
		}
	}
	
	
	@Override
	public void saveModels(List<Model> modelList) {
		Bulk.Builder bulk = new Bulk.Builder();
		for(Model model : modelList) {
			Index index = new Index.Builder(model).index(ModelConstant.INDEX_NAME).type(ModelConstant.TYPE).build();
			bulk.addAction(index);
		}		
		try {
			jestClient.execute(bulk.build());
			logger.info("ElasticSearch插入完成");
		} catch (IOException e) {
			logger.error(e.getMessage());
		}
	}
	
	@Override
	public List<Model> searchModel(String searchContent){
		SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
		searchSourceBuilder.query(QueryBuilders.matchQuery("name",searchContent));
		Search search = new Search.Builder(searchSourceBuilder.toString())
				.addIndex(ModelConstant.INDEX_NAME).addType(ModelConstant.TYPE).build();
		try {
			JestResult result = jestClient.execute(search);
			return result.getSourceAsObjectList(Model.class);
		} catch (IOException e) {
			logger.error(e.getMessage());
		}
		return null;		
	}
}
